import { PlayerInfo, RecvFromServerInfo, RoomInfo, UpdateCustomPropertiesResponse, UpdateCustomStatusResponse } from "../../GOBE/GOBE";
import PlayeItem from "../Common/PlayeItem";
import { LockType, RoomType, SceneType } from "../CommonValue";
import GameUtils from "../GameUtils";
import { Global } from "../Global";
import NetSender from "../NetWork/NetSender";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Room extends cc.Component {
    @property(cc.Prefab)
    playerItemPre: cc.Prefab = null;

    @property(cc.Prefab)
    dialogPrefab: cc.Prefab = null;


    @property(cc.EditBox)
    houseIdEditBox: cc.EditBox = null;

    @property(cc.EditBox)
    roomIdEditBox: cc.EditBox = null;

    @property(cc.EditBox)
    chatBox: cc.EditBox = null;


    @property(cc.Label)
    chatContent: cc.Label = null;

    @property(cc.Node)
    owner: cc.Node = null;

    @property([cc.Node])
    commonPlayers: cc.Node[] = [];

    @property(cc.Node)
    startBtn: cc.Node = null;

    @property(cc.Node)
    kickBtn: cc.Node = null;

    //解散房间
    @property(cc.Node)
    dismissBtn: cc.Node = null;

    @property(cc.Node)
    enableReadyBtn: cc.Node = null;

    @property(cc.Node)
    cancelReadyBtn: cc.Node = null;

    @property(cc.Node)
    leaveBtn: cc.Node = null;

    @property(cc.Toggle)
    isLockRoom: cc.Toggle = null;

    @property(cc.Label)
    isLockText: cc.Label = null;

    @property(cc.Node)
    loadingTip: cc.Node = null;

    // 实际的房主的item节点
    public ownerItemCtrl: PlayeItem = null;

    // 实际的普通玩家的item节点
    public playerItemCtrls: PlayeItem[] = [];

    // 是否是加载状态
    isLoadingStatus = false;

    start(): void {
        this.initView();
        this.initDialog();
        // Global.Inst().room.startFrameSync().then(() => {
        //     // 开始帧同步成功
        //     GameUtils.Log("开始帧同步成功");
        //     Global.Inst().room.stopFrameSync()
        // }).catch((e) => {
        //     // 开始帧同步失败
        //     console.error("提示", "开始帧同步失败", e);
        // });
        // if (Global.Inst().room.isSyncing) {
        //     this.onDirectStartFrameSync();
        // }
    }
    onDisable() {
        // 关闭对话框
        if (Global.Inst().room) {
            Global.Inst().room.removeAllListeners();
        }
    }

    initView() {
        this.initRoomView();
        this.initListener();
    }

    initDialog() {
        let ownerItem = cc.instantiate(this.playerItemPre);
        this.owner.addChild(ownerItem);
        this.ownerItemCtrl = ownerItem.getComponent(PlayeItem);
        let playerItem = cc.instantiate(this.playerItemPre);
        for (let index = 0; index < this.commonPlayers.length; index++) {
            let playerItem = cc.instantiate(this.playerItemPre);
            this.commonPlayers[index].addChild(playerItem);
            this.playerItemCtrls.push(playerItem.getComponent(PlayeItem));
        }
    }

    onDirectStartFrameSync() {
        // global.room.players.forEach(function (player) {
        //     if (global.playerId == player.playerId) {
        //         if (player.customPlayerProperties != null && player.customPlayerProperties == "watcher") {
        //             global.gameSceneType = GameSceneType.FOR_WATCHER;
        //             cc.director.loadScene("game");
        //             return;
        //         }
        //     }
        // });
        // global.gameSceneType = GameSceneType.FOR_GAME;
        cc.director.loadScene(SceneType.GAME);
    }
    initRoomView() {
        // 设置对话框
        // const dialogNode = cc.instantiate(this.dialogPrefab) as cc.Node;
        // dialogNode.parent = this.node;

        if (Global.Inst().room) {
            Global.Inst().room.update().then(() => this.setRoomView()).catch((error) => {
                if (error.code && error.code === 101005) {
                    cc.director.loadScene(SceneType.MATCH);
                }
            });
        }
    }

    initListener() {

        // 监听玩家属性变化，目前用于聊天
        Global.Inst().room.onUpdateCustomProperties(this.onUpdateCustomProperties.bind(this));

        // 监听玩家状态变化
        Global.Inst().room.onUpdateCustomStatus(this.onUpdateCustomStatus.bind(this));

        // 监听房间新玩家加入房间
        Global.Inst().room.onJoin(this.onJoining.bind(this));
        Global.Inst().room.onLeave(this.onLeaving.bind(this));

        Global.Inst().room.onRoomPropertiesChange(this.onRoomPropertiesChange.bind(this));


        // SDK 开始帧同步
        Global.Inst().room.onStartFrameSync(this.onStartFrameSync.bind(this));
        Global.Inst().room.onRecvFromServer(this.onReceiveFromGameServer.bind(this));
    }


    setRoomView() {
        const roomInfo = Global.Inst().room;
        let playerId = [];
        let readyStatus = 0;
        // if (roomInfo.players.length == 2) {
        roomInfo.players.forEach(function (player) {
            if (player.playerId != roomInfo.ownerId) {
                playerId.push(player.playerId);
                readyStatus = player.customPlayerStatus;
            }
        });
        // }
        // 设置文本标签

        this.ownerItemCtrl.setName(roomInfo.ownerId === undefined ? "" : roomInfo.ownerId);
        this.ownerItemCtrl.isOwner(true);
        this.ownerItemCtrl.setReadyStatusByString("");


        for (let index = 0; index < this.playerItemCtrls.length; index++) {
            this.playerItemCtrls[index].setName(playerId[index] ? playerId[index] : "");
            this.playerItemCtrls[index].isOwner(false);
            this.playerItemCtrls[index].setReadyStatusByString("");
        }

        this.loadingTip.active = this.isLoadingStatus;
        if (this.isLoadingStatus) {
            this.loadingTip.active = this.isLoadingStatus;
        }
        else {
            this.houseIdEditBox.string = "游戏id：" + (roomInfo.roomCode || "");
            this.roomIdEditBox.string = "联机房间id：" + (roomInfo.roomId || "");
        }

        this.initDefaultBtn(
            roomInfo.ownerId === Global.Inst().playerId,
            roomInfo.players.length,
            // readyStatus === 1,
            true,
            roomInfo.isLock == LockType.Locked
        );
    }
    // 初始化默认按钮
    initDefaultBtn(isOwner: boolean, playerCount: number, commonPlayerReady: boolean, isLock: boolean) {

        // 房间有两人时，得看是初始化房主还是非房主的界面
        if (isOwner) {
            this.enableReadyBtn.active = false;
            this.cancelReadyBtn.active = false;
            // 房主显示是否锁定房间的checkBox
            this.isLockRoom.node.active = true;
            this.isLockRoom.isChecked = isLock;
            this.isLockText.string = '是否锁定房间';
            // 加载状态时，非房主肯定是已准备状态
            if (this.isLoadingStatus) {
                this.setStartBtn(true);
                this.setKickBtn(true);
                this.setDismissBtn(true);
                this.setLeaveBtn(true, false);
            } else {
                // 非加载状态时，要看非房主的准备状态
                this.setStartBtn(true, commonPlayerReady);
                this.setKickBtn(true, true);
                this.setDismissBtn(true, true);
                this.setLeaveBtn(true, true);
            }
        } else {
            // 非房主
            // this.enableReadyBtn.active = !commonPlayerReady;
            // this.cancelReadyBtn.active = commonPlayerReady;
            this.enableReadyBtn.active = false;
            this.cancelReadyBtn.active = false;
            // 非房主不显示是否锁定房间的checkBox
            this.isLockRoom.node.active = false;
            this.isLockText.string = isLock ? '房间已锁定' : '房间未锁定';
            this.setStartBtn(false);
            this.setKickBtn(false);
            this.setDismissBtn(false);
            this.setLeaveBtn(true, !commonPlayerReady);
        }
        // this.playerItemCtrl.setReadyStatusByString(commonPlayerReady ? "已准备" : "未准备");
    }


    // 设置开始按钮
    private setStartBtn(active, enable = false) {
        this.startBtn.active = active;
        this.startBtn.getComponent(cc.Button).interactable = enable;
    }

    // 设置踢人按钮
    private setKickBtn(active, enable = false) {
        this.kickBtn.active = active;
        this.kickBtn.getComponent(cc.Button).interactable = enable;
    }

    // 设置解散按钮
    private setDismissBtn(active, enable = false) {
        this.dismissBtn.active = active;
        this.dismissBtn.getComponent(cc.Button).interactable = enable;
    }


    // 设置离开按钮
    private setLeaveBtn(active, enable) {
        this.leaveBtn.active = active;
        // this.leaveBtn.getComponent(cc.Button).interactable = enable;
    }



    // ====================按钮事件====================

    // 锁定与解锁房间
    LockRoom() {
        if (Global.Inst().room && Global.Inst().room.ownerId === Global.Inst().room.playerId) {
            Global.Inst().room.updateRoomProperties({ roomType: 'lock-type', isLock: this.isLockRoom.isChecked ? LockType.Locked : LockType.UnLocked });
        }
    }

    //发送聊天内容
    SendContent() {
        Global.Inst().player.updateCustomProperties(this.chatBox.string);
        this.chatBox.string = '';
    }

    LeaveRoom() {
        GameUtils.Log(`正在退出房间`);
        Global.Inst().client.leaveRoom().then((client) => {
            // 退出房间成功
            GameUtils.Log("退出房间成功");
            // Global.Inst().roomType = RoomType.NULL;
            Global.Inst().client = client;
            cc.director.loadScene(SceneType.HAll);
        }).catch((e) => {
            // 退出房间失败
            GameUtils.Log("退出房间失败" + e);
            // Dialog.open("提示", "退出房间失败" + Util.errorMessage(e));
        });
    }

    // 准备
    Ready() {
        GameUtils.Log(`准备就绪`);
        let ready = 1;
        Global.Inst().player.updateCustomStatus(ready);
    }

    // 取消准备
    CancelReady() {
        GameUtils.Log(`取消准备`);
        let unready = 0;
        Global.Inst().player.updateCustomStatus(unready);
    }


    startGame() {
        GameUtils.Log(`正在开始游戏`);
        Global.Inst().room.update().then((room) => {
            // let readyStatus = 0;
            // room.players.forEach(function (player) {
            //     if (player.playerId != room.ownerId) {
            //         // @ts-ignore
            //         readyStatus = player.customPlayerStatus;
            //         return;
            //     }
            // });
            // if (readyStatus === 0) {
            //     console.error("提示", "还有玩家未准备，请稍后！");
            // } else {
            // 全部加载完毕则开始帧同步
            Global.Inst().room.startFrameSync().then(() => {
                // 开始帧同步成功
                GameUtils.Log("开始帧同步成功");
            }).catch((e) => {
                // 开始帧同步失败
                console.error("提示", "开始帧同步失败", e);
            });
            // }
        });
    }

    startLoading() {
        // // 加载过程中不允许解散、退出、踢人操作
        // this.setDismissBtn(true);
        // this.setKickBtn(true);
        // this.setLeaveBtn(true, false);
        // this.setStartBtn(true);
        // this.cancelReadyBtn.getComponent(Button).interactable = false;

        // this.houseIdEditBox.string = "";
        // this.roomIdEditBox.string = "";
        // this.isLoadingStatus = true;
        // this.loadingTip.active = true;
        // let ownerProgress = this.ownerItem.getChildByName('progressBar');
        // let playerProgress = this.playerItem.getChildByName('progressBar');

        // ownerProgress.active = true;
        // ownerProgress.getComponent(cc.ProgressBar).progress = 0;

        // this.playerItem.getChildByName('player_ready_status').active = false;
        // playerProgress.active = true;
        // playerProgress.getComponent(cc.ProgressBar).progress = 0;
    }

    mockLoadingProgress(self) {
        // let increment = 0.1 * (Math.ceil(Math.random() * 12345 + 1) % 4);
        // let progress = (global.client.playerId === global.client.room.ownerId) ?
        //     self.ownerItem.getChildByName('progressBar').getComponent(cc.ProgressBar).progress :
        //     self.playerItem.getChildByName('progressBar').getComponent(cc.ProgressBar).progress;
        // progress = (progress + increment > 1) ? 1 : progress + increment;
        Global.Inst().client.room.sendToServer(JSON.stringify({
            playerId: Global.Inst().client.playerId,
            type: "Progress",
            progress: "1",
        }));
    }
    // ====================SDK广播====================
    private onJoining() {
        GameUtils.Log("SDK广播--加入房间");
        // 加入房间后
        this.initRoomView()
    }

    private onLeaving() {
        GameUtils.Log("SDK广播--离开房间");
        // 加入房间后
        this.initRoomView()
    }





    onStartFrameSync() {
        // cc.director.loadScene(SceneType.GAME);
        this.startLoading();
        this.mockLoadingProgress(this);
    }

    // 接收实时服务器消息
    onReceiveFromGameServer(data: RecvFromServerInfo) {
        let self = this;
        if (data.msg) {
            let parseMsg = JSON.parse(data.msg);
            let progress = parseMsg.progress;
            let playerId = parseMsg.playerId;
            if (progress) {
                // 此处要区分玩家，针对不同玩家渲染独立的progressBar
                if (playerId === Global.Inst().client.room.ownerId) {
                    // this.owner.getChildByName('progressBar').getComponent(cc.ProgressBar).progress = progress;
                    this.ownerItemCtrl.node.getChildByName('label').getComponent(cc.Label).string = progress;
                    this.ownerItemCtrl.node.getChildByName('label').active = true;
                }
                //  else {
                //     // this.commonPlayer.getChildByName('progressBar').getComponent(cc.ProgressBar).progress = progress;
                //     this.playerItemCtrl.node.getChildByName('label').getComponent(cc.Label).string = progress;
                //     this.playerItemCtrl.node.getChildByName('label').active = true;
                // }

            }
            const randomSec = Math.ceil(Math.random() * 1000);
            if (progress < 1 && playerId === Global.Inst().client.room.playerId) {
                setTimeout(self.mockLoadingProgress, randomSec, self);
            }
        }

        // 检测是否都已加载完毕
        // if (this.ownerItemCtrl.node.getChildByName('label').getComponent(cc.Label).string === "1" &&
        //     this.playerItemCtrl.node.getChildByName('label').getComponent(cc.Label).string === "1") {
        if (this.ownerItemCtrl.node.getChildByName('label').getComponent(cc.Label).string === "1") {
            this.isLoadingStatus = false;
            // global.gameSceneType = GameSceneType.FOR_GAME;
            cc.director.loadScene(SceneType.GAME);
        }
    }


    // ===================属性变化====================
    private onUpdateCustomProperties(playerInfo: UpdateCustomPropertiesResponse) {
        let name = "自己 : ";
        if (playerInfo.playerId !== Global.Inst().playerId) {
            name = "对手 : "
        }
        this.chatContent.string += '\n' + name + playerInfo.customProperties;
    }

    // 修改自定义状态回调
    onUpdateCustomStatus(playerInfo: UpdateCustomStatusResponse) {
        GameUtils.Log('玩家 ' + playerInfo.playerId + ' 修改状态为 ' + playerInfo.customStatus);
        let enable = playerInfo.customStatus === 1;
        if (playerInfo.playerId === Global.Inst().playerId) {
            this.enableReadyBtn.active = !enable;
            this.cancelReadyBtn.active = enable;
            this.setLeaveBtn(true, !enable)
        } else {
            this.setStartBtn(true, enable);
        }
        // this.playerItemCtrl.setReadyStatusByString(enable ? "已准备" : "未准备");
        this.initRoomView();
    }

    // 修改房间属性回调
    private onRoomPropertiesChange(roomInfo: RoomInfo) {
        // TODO拿到roomInfo重置本地数据，刷新页面
        GameUtils.Log('onRoomPropertiesChange ' + JSON.stringify(roomInfo));
        this.isLockRoom.isChecked = roomInfo.isLock == LockType.Locked;
    }


}
